/**
 * @file 图标选择组件
 * @date 2025/11/23 11:23:50
 * @author lyqjob@yeah.net
 */

import React, { useState, useMemo, useEffect } from 'react';
import * as Icons from '@ant-design/icons';
import { Flex, Tabs, Input, message, Tooltip, Modal, Space ,Button} from 'antd';

const { confirm } = Modal;

// 图标分类
const iconCategories = {
    // 方向性图标
    directional: [
        'StepBackwardOutlined', 'StepForwardOutlined', 'FastBackwardOutlined', 'FastForwardOutlined',
        'LeftOutlined', 'RightOutlined', 'UpOutlined', 'DownOutlined',
        'DoubleLeftOutlined', 'DoubleRightOutlined', 'VerticalLeftOutlined', 'VerticalRightOutlined',
        'ArrowUpOutlined', 'ArrowDownOutlined', 'ArrowLeftOutlined', 'ArrowRightOutlined',
        'CaretUpOutlined', 'CaretDownOutlined', 'CaretLeftOutlined', 'CaretRightOutlined',
    ],

    // 提示建议性图标
    notification: [
        'BellOutlined', 'NotificationOutlined', 'AlertOutlined', 'WarningOutlined',
        'InfoCircleOutlined', 'QuestionCircleOutlined', 'CheckCircleOutlined', 'CloseCircleOutlined',
        'ExclamationCircleOutlined', 'LoadingOutlined', 'SyncOutlined', 'PauseOutlined',
        'PlayCircleOutlined', 'StopOutlined', 'SoundOutlined', 'SoundMutedOutlined',
    ],

    // 编辑类图标
    editor: [
        'EditOutlined', 'DeleteOutlined', 'CopyOutlined', 'PasteOutlined',
        'CutOutlined', 'UndoOutlined', 'RedoOutlined', 'FontSizeOutlined',
        'BoldOutlined', 'ItalicOutlined', 'UnderlineOutlined', 'StrikethroughOutlined',
        'AlignLeftOutlined', 'AlignCenterOutlined', 'AlignRightOutlined', 'AlignJustifyOutlined',
        'LinkOutlined', 'UnlinkOutlined', 'EyeOutlined', 'EyeInvisibleOutlined',
    ],

    // 数据类图标
    data: [
        'TableOutlined', 'BarChartOutlined', 'LineChartOutlined', 'PieChartOutlined',
        'AreaChartOutlined', 'DotChartOutlined', 'ArrowUpRightOutlined', 'ArrowDownRightOutlined',
        'TrendChartsOutlined', 'NumberOutlined', 'PercentageOutlined', 'WalletOutlined',
        'GoldOutlined', 'DollarOutlined', 'EuroOutlined', 'PoundOutlined',
    ],

    // 文件类图标
    file: [
        'FileOutlined', 'FileAddOutlined', 'FileTextOutlined', 'FileImageOutlined',
        'FilePdfOutlined', 'FileExcelOutlined', 'FileWordOutlined', 'FileZipOutlined',
        'FolderOutlined', 'FolderOpenOutlined', 'FolderAddOutlined', 'UploadOutlined',
        'DownloadOutlined', 'CloudUploadOutlined', 'CloudDownloadOutlined', 'CloudSyncOutlined',
    ],

    // 用户相关图标
    user: [
        'UserOutlined', 'UserAddOutlined', 'UserDeleteOutlined', 'UserSwitchOutlined',
        'TeamOutlined', 'ContactsOutlined', 'ProfileOutlined', 'SolutionOutlined',
        'CustomerServiceOutlined', 'ApiOutlined', 'LinkOutlined', 'UnlinkOutlined',
        'LockOutlined', 'UnlockOutlined', 'SafetyOutlined', 'ShieldOutlined',
    ],

    // 基础功能图标
    basic: [
        'HomeOutlined', 'MenuOutlined', 'AppstoreOutlined', 'SettingOutlined',
        'SearchOutlined', 'PlusOutlined', 'MinusOutlined', 'CloseOutlined',
        'CheckOutlined', 'QuestionOutlined', 'MoreOutlined', 'EllipsisOutlined',
        'RefreshOutlined', 'FullscreenOutlined', 'FullscreenExitOutlined', 'ZoomInOutlined',
        'ZoomOutOutlined', 'FilterOutlined', 'SortAscendingOutlined', 'SortDescendingOutlined',
    ],

    // 其他常用图标
    other: [
        'HeartOutlined', 'StarOutlined', 'LikeOutlined', 'DislikeOutlined',
        'MessageOutlined', 'CommentOutlined', 'GiftOutlined', 'ThunderboltOutlined',
        'FireOutlined', 'TagOutlined', 'RiseOutlined', 'FallOutlined',
        'CameraOutlined', 'VideoCameraOutlined', 'MicOutlined', 'CoffeeOutlined',
    ]
};

const IconPicker = ({ onChange, value, className }) => {
    const [activeKey, setActiveKey] = useState('1');
    const [searchText, setSearchText] = useState('');
    const [selectedIcon, setSelectedIcon] = useState(value || '');
    const [copiedIcon, setCopiedIcon] = useState('');


    // 当外部value变化时更新内部selectedIcon
    useEffect(() => {
        if (value && value !== selectedIcon) {
            setSelectedIcon(value);
        }
    }, [value]);

    // 根据分类和搜索文本生成图标数据
    const getIconsByCategory = useMemo(() => {
        return (category) => {
            const iconNames = iconCategories[category] || [];
            return iconNames
                .filter(name =>
                    name.toLowerCase().includes(searchText.toLowerCase()) &&
                    Icons[name] !== undefined // 过滤掉不存在的图标
                )
                .map(name => {
                    const IconComponent = Icons[name];
                    return {
                        label: <IconComponent />,
                        value: name,
                        key: name
                    };
                });
        };
    }, [searchText]);

    // 处理搜索
    const handleSearch = (value) => {
        setSearchText(value);
    };

    // 处理图标选择
    const handleIconSelect = (iconName) => {
        
        setSelectedIcon(iconName);

        if (onChange) {
            onChange(iconName);
        }
        // 点击时自动复制图标名称到剪贴板
        copyToClipboard(iconName);
    };

    // 复制图标名称到剪贴板
    const copyToClipboard = async (text) => {
        try {
            await navigator.clipboard.writeText(text);
            setCopiedIcon(text);
            message.success('图标名称已复制到剪贴板');

            // 3秒后重置复制状态
            setTimeout(() => {
                setCopiedIcon('');
            }, 3000);
        } catch (err) {
            message.error('复制失败，请手动复制');
            console.error('复制失败:', err);
        }
    };


    // 处理清空选择
    const handleClearSelection = () => {
        confirm({
            title: '确认清空选择',
            content: '确定要清空当前选择的图标吗？',
            onOk() {
                setSelectedIcon('');
                if (onChange) {
                    onChange('');
                }
                message.info('已清空选择');
            },
            onCancel() { }
        });
    };

    // 图标展示组件
    const IconDisplayComponent = ({ values }) => {
        return (
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', justifyContent: 'flex-start' }}>
                {values.length > 0 ? (
                    values.map((item) => {
                        const isSelected = selectedIcon === item.value;
                        const isCopied = copiedIcon === item.value;

                        return (
                            <Tooltip
                                key={item.key}
                                title={
                                    <div>
                                        <div>点击选择</div>
                                        {isSelected && <div style={{ color: '#1890ff' }}>当前已选择</div>}
                                        {isCopied && <div style={{ color: '#52c41a' }}>已复制</div>}
                                    </div>
                                }
                                placement="top"
                            >
                                <div
                                    style={{
                                        width: 150,
                                        height: 70,
                                        display: 'flex',
                                        flexDirection: 'column',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        cursor: 'pointer',
                                        border: isSelected ? '2px solid #1890ff' : '1px solid #f0f0f0',
                                        borderRadius: 4,
                                        transition: 'all 0.2s ease-in-out',
                                        backgroundColor: isSelected ? '#e6f7ff' : '#ffffff'
                                    }}
                                    onClick={() => handleIconSelect(item.value)}
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                                        e.currentTarget.style.transform = 'translateY(-2px)';
                                    }}
                                    onMouseLeave={(e) => {
                                        e.currentTarget.style.boxShadow = 'none';
                                        e.currentTarget.style.transform = 'translateY(0)';
                                    }}
                                >
                                    <div style={{ fontSize: 24, marginBottom: 4 }}>
                                        {item.label || '图标'}
                                    </div>
                                    <div style={{
                                        fontSize: 11,
                                        color: isSelected ? '#1890ff' : '#666',
                                        wordBreak: 'break-all',
                                        textAlign: 'center',
                                        lineHeight: 1.3,
                                        maxWidth: '90%'
                                    }}>{item.value}</div>
                                </div>
                            </Tooltip>
                        );
                    })
                ) : (
                    <div style={{
                        padding: 40,
                        color: '#999',
                        textAlign: 'center',
                        width: '100%'
                    }}>
                        <Icons.SearchOutlined style={{ fontSize: 48, marginBottom: 16, opacity: 0.3 }} />
                        <div>没有找到匹配的图标</div>
                        <div style={{ fontSize: 12, marginTop: 8 }}>尝试使用其他关键词搜索</div>
                    </div>
                )}
            </div>
        );
    };

    // 生成标签页内容
    const items = [
        {
            key: '1',
            label: '方向性图标',
            children: <IconDisplayComponent values={getIconsByCategory('directional')} />,
        },
        {
            key: '2',
            label: '提示建议性图标',
            children: <IconDisplayComponent values={getIconsByCategory('notification')} />,
        },
        {
            key: '3',
            label: '编辑类图标',
            children: <IconDisplayComponent values={getIconsByCategory('editor')} />,
        },
        {
            key: '4',
            label: '数据类图标',
            children: <IconDisplayComponent values={getIconsByCategory('data')} />,
        },
        {
            key: '5',
            label: '文件类图标',
            children: <IconDisplayComponent values={getIconsByCategory('file')} />,
        },
        {
            key: '6',
            label: '用户相关图标',
            children: <IconDisplayComponent values={getIconsByCategory('user')} />,
        },
        {
            key: '7',
            label: '基础功能图标',
            children: <IconDisplayComponent values={getIconsByCategory('basic')} />,
        },
        {
            key: '8',
            label: '其他常用图标',
            children: <IconDisplayComponent values={getIconsByCategory('other')} />,
        },
    ];

    const onTabChange = (key) => {
        setActiveKey(key);
        console.log('Active tab:', key);
    };

    return (
        <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }} className={className}>
            {/* 顶部工具栏 */}
            <div style={{ padding: 16, borderBottom: '1px solid #f0f0f0', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
                <Space.Compact style={{ width: '30%' }}>
                    <Input 
                        allowClear 
                        value={searchText}
                        placeholder={'请输入图标名称'} 
                        onChange={(e) => handleSearch(e.target.value)}
                        onPressEnter={() => handleSearch(searchText)}
                    />
                    <Button type="primary" onClick={() => handleSearch(searchText)}>搜索</Button>
                </Space.Compact>

                {/* 当前选中图标显示 */}
                {selectedIcon && (
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: 8,
                        padding: 8,
                        backgroundColor: '#f5f5f5',
                        borderRadius: 4,
                        flex: 1,
                        maxWidth: 400
                    }}>
                        <span style={{ color: '#666', fontSize: 14 }}>当前选择:</span>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1 }}>
                            {Icons[selectedIcon] && (() => { const SelectedIcon = Icons[selectedIcon]; return <SelectedIcon style={{ fontSize: 20 }} />; })()}
                            <span style={{
                                fontWeight: 500,
                                fontSize: 14,
                                wordBreak: 'break-all'
                            }}>{selectedIcon}</span>
                            <Tooltip title="复制图标名称">
                                <span
                                    style={{
                                        cursor: 'pointer',
                                        color: '#1890ff',
                                        fontSize: 12,
                                        padding: 2,
                                        borderRadius: 2,
                                        ':hover': { backgroundColor: '#e6f7ff' }
                                    }}
                                    onClick={() => copyToClipboard(selectedIcon)}
                                >
                                    复制
                                </span>
                            </Tooltip>
                        </div>
                        <Tooltip title="清空选择">
                            <span
                                style={{
                                    cursor: 'pointer',
                                    color: '#ff4d4f',
                                    fontSize: 12,
                                    padding: 2,
                                    borderRadius: 2,
                                    ':hover': { backgroundColor: '#fff1f0' }
                                }}
                                onClick={handleClearSelection}
                            >
                                清空
                            </span>
                        </Tooltip>
                    </div>
                )}
            </div>

            {/* 图标展示区域 */}
            <div style={{ flex: 1, overflow: 'auto', padding: 16 }}>
                <Tabs
                    activeKey={activeKey}
                    items={items}
                    onChange={onTabChange}
                    tabPosition="top"
                    size="default"
                    style={{ height: '100%' }}
                    tabBarStyle={{ marginBottom: 16 }}
                    className="icon-picker-tabs"
                    locale={{ emptyText: '暂无图标' }}
                />
            </div>

        </div>
    );
};

export default IconPicker;
